<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <jsp:include page="/public/inc/head.jsp"/>
    <script type="text/javascript">
        
        var $table;
        var $form1;
        $(function () {
            $form1 = $("#form1").bootstrapValidator({
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                live: 'disabled,submitted',//当点击提交时验证并展示错误信息
                message: 'This value is not valid',//通用验证信息
                fields: {
                    nickname: {
                        validators: {
                            notEmpty: {
                                message: '不能为空'
                            }
                        }
                    },
                    sex: {
                        validators: {
                            regexp: {
                                regexp: /^[1-2]*$/,
                                message: '必须选择其中的一个'
                            }
                        }
                    },
                    signature: {
                        validators: {
                            notEmpty: {
                                message: '不能为空'
                            }
                        }
                    }
                }
            });

            var tableUrl = "/system/wwdx_copywriter/list";
            tableInit(tableUrl);
            
            //查询  
            $('#searchBtn').click(function () {
                $table.bootstrapTable('refresh');
            });
            
            //清空
            $('#clearBtn').click(function () {
                $('#myform')[0].reset();
                $table.bootstrapTable('refresh');
            });

            /**
             * 添加
             */
            $('#btn_add').click(function () {
                $("#myModal").modal('show');
            });
            
            $('#submitBtn').click(function () {
                bootstrapValidator.validate();
                var valid = bootstrapValidator.isValid();
                if (valid){
                    //ajax提交表单
                    $.post("/system/wwdx_copywriter/add", $form1.serialize(), function(result) {
                        setTimeout(function (args) {
                            $("#myModal2").modal('hide');
                        },2000);
                        $table.bootstrapTable('refresh');
                    }, 'json');
                }
            });

            /**
             * 文件上传组件
             */
            var $imgFile = $("#img_file");
            //初始化上传控件的样式
            $imgFile.fileinput({
                language: 'zh', //设置语言
                uploadUrl: "/other/upload", //上传的地址
                allowedFileExtensions: ['jpg', 'png'],//接收的文件后缀
                showUpload: true, //是否显示上传按钮
                showCaption: true,//是否显示标题
                browseClass: "btn btn-primary", //按钮样式     
                dropZoneEnabled: false,//是否显示拖拽区域
                //minImageWidth: 50, //图片的最小宽度
                //minImageHeight: 50,//图片的最小高度
                //maxImageWidth: 1000,//图片的最大宽度
                //maxImageHeight: 1000,//图片的最大高度
                maxFileSize: 1000,//单位为kb，如果为0表示不限制文件大小
                maxFileCount: 1, //表示允许同时上传的最大文件个数
                enctype: 'multipart/form-data',
                validateInitialCount:true,
                previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
                msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！"
                
            }).on("fileuploaded", function (event, data, previewId, index) {
                var result = data.response;
                if(result.status === 0){
                    $("#headimg").val(result.data);
                }
            }).on('fileerror', function(event, data, msg) {
                alert(msg);
            });
            
            //文件上传
            //$imgFile.fileinput("upload");
            //文件上传完成之后的事件
            /*$imgFile.on("fileuploaded", function (event, data, previewId, index) {
                console.info(data.response.data);
            });*/
            //错误通知
            /*$imgFile.on('fileerror', function(event, data, msg) {
                alert(msg);
            });*/

            //初始化操作
            //operate.operateInit();
        });

        ko.validation.init({
            parseInputAttributes: true
        },true);


        var viewMode = {
            headimg : ko.observable(),  //和标签中的data-bind  对应
            nickname : ko.observable().extend({ required: {message: '用户名不能为空'} }),
            sex : ko.observable().extend({required: {message: '请选择'}}),
            sexOptions: [1, 2],
            signature:ko.observable().extend({ required: {message: '签名不能为空'} }),

            submit: function() {
                if (viewMode.errors().length === 0) {
                    alert('Thank you.');
                }
                else {
                    alert('Please check your submission.');
                    viewMode.errors.showAllMessages();
                }
            }
        };



        
        // 操作
        /*var operate = {
            // 初始化按钮事件
            operateInit : function() {
                this.operateAdd();
                this.operateUpdate();
                this.operateDelete();
                this.viewMode = ko.validatedObservable({
                    headimg : ko.observable(),  //和标签中的data-bind  对应
                    nickname : ko.observable().extend({ required: {message: '用户名不能为空'} }),
                    sex : ko.observable().extend({required: {message: '请选择'}}),
                    sexOptions: [1, 2],
                    signature:ko.observable().extend({ required: {message: '签名不能为空'} })
                });
            },
            // 新增
            operateAdd : function() {
                $('#btn_add').click(function() {
                    $("#myModal").modal().on("shown.bs.modal", function() {
                        ko.applyBindings(operate.viewMode, document.getElementById("myModal"));
                        operate.operateSave("/system/wwdx_copywriter/save");
                    }).on('hidden.bs.modal', function() {
                        ko.cleanNode(document.getElementById("myModal"));
                    });
                });
            },
            // 编辑  把弹出页面中input中的data-bind中value:name 换成value:你后台传来的变量名称                 
            operateUpdate : function() {
                $('#btn_edit').on("click", function() {
                    var arrselectedData = $table.bootstrapTable('getSelections');
                    if (!operate.operateCheck(arrselectedData)) {
                        return;
                    }
                    $("#myModal").modal().on("shown.bs.modal", function() {
                        // 将选中该行数据有数据Model通过Mapping组件转换为viewmodel
                        ko.utils.extend(operate.viewMode, ko.mapping.fromJS(arrselectedData[0]));
                        ko.applyBindings(operate.viewMode, document.getElementById("myModal"));
                        operate.operateSave("/system/wwdx_copywriter/edit");
                    }).on('hidden.bs.modal', function() {
                        ko.cleanNode(document.getElementById("myModal"));
                    });
                });
            },
            // 删除
            operateDelete : function() {  //当点击删除的时候  会进入这个方法
                $('#btn_delete').on("click", function() {
                    var arrselectedData = $table.bootstrapTable('getSelections');
                    if (arrselectedData.length <= 0) {
                        alert("请选中一行");
                    } else {
                        var idList = [];
                        $.each(arrselectedData,function (index, obj) {
                            idList.push(obj.userid);
                        });
                        $.ajax({
                            url : "/system/wwdx_copywriter/delete",
                            type:'post',
                            data:{"idList":idList},
                            success:function (result) {
                                alert(result.message);
                                $table.bootstrapValidator('refresh')
                            }
                        });
                    }
                });
            },
            // 保存数据
            operateSave : function(url) {  //当点击保存的时候回跳到这个方法
                /!*$('#btn_submit').on("click", function() {

                });*!/
                // 取到当前的viewmodel
                var oViewModel = operate.viewMode;
                // 将Viewmodel转换为数据model
                var oDataModel = ko.toJS(oViewModel);
                var valid = oViewModel.isValid();
                console.info(valid);
                $.ajax({
                    url : url,  //url
                    type : "post",
                    data : $form1.serialize(),
                    success : function(result) {
                        alert(result.message);
                        $table.bootstrapTable('refresh');
                    }
                });
            },
            // 数据校验
            operateCheck : function(arr) {
                if (arr.length <= 0) {
                    alert("请至少选择一行数据");
                    return false;
                }
                if (arr.length > 1) {
                    alert("只能编辑一行数据");
                    return false;
                }
                return true;
            }
        };*/


        /**
         * 用户表格列表
         */
        function tableInit(url) {
            $table = $("#table").bootstrapTable({
                url: url,                           //请求后台的URL（*）
                cache: false,
                striped: true,                      //是否显示行间隔色
                sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                pagination: true,                   //是否显示分页（*）
                pageNumber:1,                       //初始化加载第一页，默认第一页
                pageSize: 15,                       //每页的记录行数（*）
                pageList: [10,15, 25, 50, 100],     //可供选择的每页的行数（*）
                paginationPreText:'上一页',
                paginationNextText:'下一页',
                toolbar:"#toolbar",
                uniqueId: "userid",                     //每一行的唯一标识，一般为主键列
                //得到查询的参数
                queryParams : function (params) {
                    return {
                        rows: params.limit,                         //页面大小
                        page: (params.offset / params.limit) + 1,    //页码
                        status:$("#status").val(),
                        type:$("#type").val()
                    };
                },
                columns: [{
                     field: 'ck',
                     checkbox: true
                },{
                    title : '序号',
                    align: "center",
                    width: 40,
                    formatter: function (value, row, index) {
                        //获取每页显示的数量
                        var pageSize = $table.bootstrapTable('getOptions').pageSize;
                        //获取当前是第几页  
                        var pageNumber = $table.bootstrapTable('getOptions').pageNumber;
                        //返回序号，注意index是从0开始的，所以要加上1
                        return pageSize * (pageNumber - 1) + index + 1;
                    }
                }, {
                    field: 'headimg',
                    title: '头像',
                    formatter:function (value) {
                        return "<img src=\"http://img.readerday.com/face/"+value+"\" style=\"height: 70px;width: 70px;\">";
                    }
                }, {
                    field: 'nickname',
                    title: '撰稿人'
                }, {
                    field: 'sex',
                    title: '性别',
                    formatter:function (value) {
                        var sex;
                        if (value === 1){
                            sex = "男";
                        }else if (value === 2){
                            sex = "女";
                        }else {
                            sex = "未知";
                        }
                        return sex;
                    }
                }, {
                    field: 'gmtCreated',
                    title: '创建时间'
                }],
                onLoadSuccess: function () {
                },
                onLoadError: function () {
                    alert("数据加载失败！");
                },
                onDblClickRow: function (row, $element) {
                }
            });
        }
    </script>
</head>
<body>
<div id="header" class="navbar navbar-static-top" role="navigation">
    <jsp:include page="/public/inc/top.jsp"/>
</div>
<div class="container-fluid" style="margin-top:5px;margin-bottom:60px;">
    <div class="row">
        <jsp:include page="/public/inc/menu.jsp"/>
        <div class="col-xs-12 col-sm-10">
            <%--<div id="toolbar">
                <form id="myform">
                    <label>
                        <select id="status" name="status" class="form-control">
                            <option value="">支付类型</option>
                            <option value="1">已支付</option>
                            <option value="0">未支付</option>
                        </select>
                    </label>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <label>
                        <select id="type" name="type" class="form-control">
                            <option value="">产品类型</option>
                            <option value="1">阅读包</option>
                            <option value="2">解读版</option>
                            <option value="3">阅读币</option>
                            <option value="7">会员</option>
                        </select>
                    </label>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <button type="button" id="searchBtn" class="btn btn-default">筛选</button>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <button type="reset" id="clearBtn" class="btn btn-default">清空</button>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <button type="button" id="exportExcel" class="btn btn-default">Excel</button>
                </form>
            </div>--%>
            <div id="toolbar" class="btn-group">
                <button id="btn_add" type="button" class="btn btn-default">
                    <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
                </button>
                <button id="btn_edit" type="button" class="btn btn-default">
                    <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
                </button>
                <button id="btn_delete" type="button" class="btn btn-default">
                    <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
                </button>
            </div>
            <table id="table"></table>
            <%--<div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel2" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                            <h4 class="modal-title" id="myModalLabel2">通知</h4>
                        </div>
                        <div id="showInfo2" class="modal-body">
                            <form id="form1" class="form-horizontal" role="form">
                                <div class="form-horizontal">
                                    <div class="form-group">
                                        <label class="control-label col-md-2">撰稿人</label>
                                        <div class="col-md-10">
                                            <input id="nickname" name="nickname" class="form-control" placeholder="请输入撰稿人"/>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="control-label col-md-2">性别</label>
                                        <div class="col-md-10">
                                            <select name="sex" class="form-control">
                                                <option value="0">请选择</option>
                                                <option value="2">女</option>
                                                <option value="1">男</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="control-label col-md-2">头像</label>
                                        <div class="col-md-10">
                                            <input type="hidden" id="headimg" name="headimg" />
                                            &lt;%&ndash;单文件上传&ndash;%&gt;
                                            <input type="file" id="img_file" class="file-loading" />
                                            &lt;%&ndash;多文件上传&ndash;%&gt;
                                            &lt;%&ndash;<input type="file" name="headimg" id="txt_file" multiple class="file-loading" />&ndash;%&gt;
                                           &lt;%&ndash; <input type="hidden" name="headimg" />
                                            <input type="file" class="btn btn-primary" name="HeadImg"/>
                                            <img src="http://img.readerday.com/face/" class="thumbnail" style="height: 200px;">&ndash;%&gt;
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="control-label col-md-2">签名</label>
                                        <div class="col-md-10">
                                            <textarea name="signature" id="signature" class="form-control" placeholder="请输入签名" ></textarea>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                            <button id="submitBtn" type="button" class="btn btn-primary">提交更改</button>
                        </div>
                    </div>
                </div>
            </div>--%>
            <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                            <h4 class="modal-title" id="myModalLabel">撰稿人表单</h4>
                        </div>
                        <div class="modal-body">
                            <form id="form1" class="form-horizontal" role="form">
                                <div class="form-horizontal">
                                    <div class="form-group">
                                        <label class="control-label col-md-2">撰稿人</label>
                                        <div class="col-md-10">
                                            <input id="nickname" name="nickname" data-bind="textInput:nickname" class="form-control" placeholder="请输入撰稿人"/>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="control-label col-md-2">性别</label>
                                        <div class="col-md-10">
                                            <select id="sex" name="sex" data-bind="textInput: sex, options: sexOptions, optionsCaption: '请选择'" class="form-control">
                                                <option value="0">请选择</option>
                                                <option value="2">女</option>
                                                <option value="1">男</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="control-label col-md-2">头像</label>
                                        <div class="col-md-10">
                                            <input type="hidden" id="headimg" name="headimg" data-bind="textInput:headimg" />
                                            <%--单文件上传--%>
                                            <input type="file" id="img_file" class="file-loading" />
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="control-label col-md-2">签名</label>
                                        <div class="col-md-10">
                                            <textarea name="signature" id="signature" data-bind="textInput:signature" class="form-control" placeholder="请输入签名" ></textarea>
                                        </div>
                                    </div>
                                </div>
                            </form>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>关闭</button>
                                <button type="button" data-bind='click: submit' class="btn btn-primary" data-dismiss="modal"><span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span>保存</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<jsp:include page="/public/inc/bottom.jsp"/>
</body>
</html>